﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Network;
using GameProtocols;

public class LockstepServer : MonoBehaviour {

    int FrameNo;
    List<PKG_FRAME> frames;

    void Start ()
    {
        FrameNo = 0;
        frames = new List<PKG_FRAME>();
        NetManager.Instance.UdpLoopback = true;
        NetManager.Instance.RegistMsg((ushort)ProtoId.MSG_OPERATION, onRecvInput);
        NetManager.Instance.RegistMsg((ushort)ProtoId.MSG_SYN_STATE_REQ, onSyncState);
        
    }
	
	void FixedUpdate ()
    {
        PKG_FRAME frame = new PKG_FRAME();
        frame.frameNo = FrameNo;
        if (receivedInput)
        {
            DT_FRAME_CONTENT frameContent = new DT_FRAME_CONTENT();
            frameContent.playerId = PlayerManager.Instance.MyPlayerID;
            frameContent.operation = operation;
            frame.operations.Add(frameContent);
        }
        
        NetManager.Instance.SendUdpMessage((ushort)ProtoId.MSG_FRAME, frame);
        frames.Add(frame);
        FrameNo++;
        receivedInput = false;
    }

    private void OnDestroy()
    {
        NetManager.Instance.UdpLoopback = false;
        NetManager.Instance.UnregistMsg((ushort)ProtoId.MSG_OPERATION, onRecvInput);
        NetManager.Instance.UnregistMsg((ushort)ProtoId.MSG_SYN_STATE_REQ, onSyncState);
    }

    int operation;
    bool receivedInput;

    void onRecvInput(object msg)
    {
        PKG_OPERATION proto = (PKG_OPERATION)msg;
        operation = proto.operation;
        receivedInput = true;
    }

    void onSyncState(object msg)
    {
        PKG_SYN_STATE_REQ proto = (PKG_SYN_STATE_REQ)msg;
        int frameNo = proto.frameNo;
        PKG_SYN_STATE_NTF ret = new PKG_SYN_STATE_NTF();
        int startIndex = frames.FindIndex((PKG_FRAME aframe) => aframe.frameNo == frameNo);
        if (startIndex < 0)
            return;
        int count = frames.Count - startIndex;
        ret.frames.AddRange(frames.GetRange(startIndex, count));
        NetManager.Instance.SendUdpMessage((ushort)ProtoId.MSG_SYN_STATE_NTF, ret);
    }
}
